package conchmusic.conchmusicclient.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.adapter.SearchAdapter;
import conchmusic.conchmusicclient.dao.ClientControl;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.pojo.HistoryInfo;
import conchmusic.conchmusicclient.pojo.Song;
import conchmusic.conchmusicclient.thread.QueryThread;
import conchmusic.conchmusicclient.util.GetSongCommand;
import conchmusic.conchmusicclient.util.HistoryResolve;
import conchmusic.conchmusicclient.util.InitPlayBar;
import conchmusic.conchmusicclient.util.Invoker;
import conchmusic.conchmusicclient.util.JsonParser;
import conchmusic.conchmusicclient.view.PlayBar;
import conchmusic.conchmusicclient.view.SearchView;

public class OnlineSearchActivity extends AppCompatActivity implements SearchView.SearchViewListener {
    private List<Song> dbData;
    private ListView lvResults;
    private SearchView searchView;
    private ArrayAdapter<String> hintAdapter;
    private ArrayAdapter<String> autoCompleteAdapter;
    private SearchAdapter resultAdapter;
    private ArrayList<String> hintData;
    private List<String> autoCompleteData;
    private List<Song> resultData;
    private static int DEFAULT_HINT_SIZE = 4;
    private static int hintSize = DEFAULT_HINT_SIZE;
    private ArrayList<String> onlineHisArrayList;
    private ArrayList<HistoryInfo> onlineHisInfosList;
    private HistoryResolve historyResolve;
    private ListView historyListView;
    private TextView clearHistory;
    private ArrayAdapter<String> adapter_history;
    private String selectHistory = null;
    private String info = null;
    private View view;
    private JsonParser jsonParser;
    private PlayBar playBar;
    private Button btn_play;
    private Intent intent;
    private int uid;
    private MyDBHelp myDBHelp;
    private ClientControl clientControl;
    private Handler downSongHandler;
    private InitPlayBar initPlayBar;
    private boolean invaliFla=false;
    private List<Song> completeData;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        setContentView(R.layout.activity_online_search);
        myDBHelp=new MyDBHelp(this,"demon",null,1);
        clientControl=new ClientControl(myDBHelp);
        completeData=new ArrayList<>();
        jsonParser = new JsonParser();
        dbData=new ArrayList<>();
        initHistoryData();
        initData();
        initViews();
        downSongHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                String downloadInfo=msg.getData().getString("download");
                if(downloadInfo.equals("DownloadSuccess")){
                    Toast.makeText(OnlineSearchActivity.this,"下载状态:"+downloadInfo,Toast.LENGTH_SHORT).show();
                }
            }
        };

    }

    public void initViews() {
        view = findViewById(R.id.online_history_linearLayout);
        lvResults = (ListView) findViewById(R.id.online_search_results);
        searchView = (SearchView) findViewById(R.id.online_search_layout);
        searchView.setSearchViewListener(this);
        searchView.setTipsHintAdapter(hintAdapter);
        searchView.setAutoCompleteAdapter(autoCompleteAdapter);
        searchView.setHistoryView(view);
        btn_play=(Button)findViewById(R.id.playbar_play);
        playBar=(PlayBar)findViewById(R.id.online_playbar);
        initPlayBar=new InitPlayBar(playBar,this);
        initPlayBar.initPlaybar();
        lvResults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                initPlayBar.itemInitPlaybar();
                String[] list=new String[resultData.size()];
                for(Song song:resultData){
                    song.setLocalSongId(0);
                    clientControl.addSong(song);
                }
                for(int i=0;i<resultData.size();i++){
                    Song onlineSong=clientControl.findCloudSong(resultData.get(i));
                    list[i]=Integer.toString(onlineSong.getLocalSongId());
                    Log.i("onlineSong",onlineSong.getTitle()+"..."+onlineSong.getLocalSongId());
                }
                String[] list0=new String[]{list[position]};
                intent=playMusic(position,list);
                //intent=playMusic(0,list0);
                Log.i("songId in online",list[position]+"...");
                btn_play.setBackgroundResource(R.mipmap.ic_pause);
                startService(intent);
            }
        });
        clearHistory = (TextView) findViewById(R.id.online_clear_history_textview);
        historyListView = (ListView) findViewById(R.id.online_history_list);
        clearHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                historyResolve.clearOnlineHistory();
                onlineHisArrayList.clear();
                adapter_history.notifyDataSetChanged();
            }
        });
        makeAdapter();
    }

    public void initData() {
        getHintData();
        getAutoCompleteData(null);
        getResultData(null);
    }

    public void initHistoryData() {
        onlineHisArrayList = new ArrayList<>();
        historyResolve = new HistoryResolve(this);
        onlineHisInfosList = historyResolve.getOnlineHistory();
        for (HistoryInfo hisInfo : onlineHisInfosList) {
            onlineHisArrayList.add(hisInfo.getHistory());
        }
    }

    public void makeAdapter() {
        adapter_history = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, onlineHisArrayList);
        historyListView.setAdapter(adapter_history);
        historyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectHistory = historyListView.getAdapter().getItem(position).toString();
                info = onlineHisInfosList.get(position).getInfo();
                initLvResult();
            }
        });
    }

    public void initLvResult() {
        view.setVisibility(View.GONE);
        if (info == null || selectHistory == null) {
            return;
        } else {
            onlineHisSearch(selectHistory);
        }
    }

    @Override
    public void onSearch(String text, String flag) {
        view.setVisibility(View.GONE);
        if ("SearchAction".equals(flag)) {
            getResultData(text);
            Log.i("OnlineSearch188",text);
        } else if ("ItemOnclick".equals(flag)) {
            getCurResultData(text);
        }
        lvResults.setVisibility(View.VISIBLE);
        if (lvResults.getAdapter() == null) {
            lvResults.setAdapter(resultAdapter);
        } else {
            resultAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onRefreshAutoComplete(String text) {
        if("".equals(text)){
            autoCompleteData.clear();
            autoCompleteAdapter.notifyDataSetChanged();
        }else{
            getAutoCompleteData(text);
        }
    }

    @Override
    public void clearResult() {
        lvResults.setVisibility(view.GONE);
        autoCompleteData.clear();
        view.setVisibility(View.GONE);
    }

    private void getHintData() {
        hintData = new ArrayList<>(hintSize);
        hintAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, hintData);
    }

    private void getResultData(String text) {
        if (resultData == null) {
            // 初始化
            resultData = new ArrayList<>();
        } else {
            resultData.clear();
            textSearch(text);
        }
        if (resultAdapter == null) {
            resultAdapter = new SearchAdapter(this, resultData);
        }
    }

    public void getCurResultData(String text) {
        String[] songAndSinger=text.split("\\+");
        String songName=songAndSinger[0];
        String singer=songAndSinger[1];
        if (resultData == null) {
            // 初始化
            resultData = new ArrayList<>();
        } else {
            resultData.clear();
            dbData=sortSong(dbData);
            for(Song song:dbData){
                List<String> artistNamesList=song.getArtistNames();
                String artistName="";
                for(String artist:artistNamesList){
                    artistName=artistName+artist+" ";
                }
                if(song.getTitle().equals(songName)&&artistName.equals(singer)){
                    resultData.add(song);
                    Log.i("OnlineSearch241",song.getTitle()+song.getArtistNames());
                }
            }
        }
        if (resultAdapter == null) {
            resultAdapter = new SearchAdapter(this, resultData);
        }else{
            resultAdapter.notifyDataSetChanged();
        }
    }

    private void getAutoCompleteData(String text) {
        if (autoCompleteData == null) {
            //初始化
            autoCompleteData = new ArrayList<String>();
        } else{
            autoCompleteData.clear();
            try {
                text.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            onlineSearch(text);
        }
        if(autoCompleteAdapter == null){
            autoCompleteAdapter=new ArrayAdapter<String>(OnlineSearchActivity.this,android.R.layout.simple_list_item_1,autoCompleteData);
        }
    }

    //需要改为在线播放
    public Intent playMusic(int position,String[] list){
        Intent intent=new Intent();
        intent.putExtra("action","playDirect");
        intent.putExtra("posit",position);
        intent.putExtra("songList",list);
        intent.setAction("music2");
        intent.setPackage(OnlineSearchActivity.this.getPackageName());
        return intent;
    }
    protected void onResume() {
        super.onResume();
        playBar.startMsgReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        playBar.closeMsgReceiver();
    }
    public int getUid(){
        //注意修改
        this.uid=1;
        return this.uid;
    }
    public void onlineHisSearch(String text){
        Log.i("onlineHisSearch280",text);
        text=text.split("\\+")[0];
        GetSongCommand getSongCommand = new GetSongCommand(getResources(), text);
        Invoker invoker = new Invoker();
        invoker.setTransferCommand(getSongCommand);
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String autoCompletemsg = msg.getData().getString("json");
                Log.i("autoCompletemsg288",autoCompletemsg);
                resultData.clear();
                resultData=getdbData(autoCompletemsg);
                if(resultData.size()==0){
                    Toast.makeText(OnlineSearchActivity.this,"没有此歌曲",Toast.LENGTH_SHORT).show();
                    Log.i("onlineHisSearch293","没有此歌曲");
                }else{
                    lvResults.setVisibility(View.VISIBLE);
                    resultAdapter = new SearchAdapter(OnlineSearchActivity.this, resultData);
                    lvResults.setAdapter(resultAdapter);
                }
                view.setVisibility(View.GONE);

            }
        };
        QueryThread queryThread=new QueryThread(invoker,handler);
        Thread thread=new Thread(queryThread);
        thread.start();
    }
    public void onlineSearch(String text){
        text=text.split("\\+")[0];
        GetSongCommand getSongCommand = new GetSongCommand(getResources(), text);
        Invoker invoker = new Invoker();
        invoker.setTransferCommand(getSongCommand);
        final String playText=text;
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String autoCompletemsg = msg.getData().getString("json");
                completeData.clear();
                completeData.addAll(getdbData(autoCompletemsg));
                if(!invaliFla){
                    dbData.clear();
                    autoCompleteData.clear();
                    Log.i("OnlineSearchActivity329",Integer.toString(completeData.size()));
                    for(int i=0,size=0;i<completeData.size()&&size<6;i++){
                        Song autoSong=completeData.get(i);
                        List<String> artistNamesList=autoSong.getArtistNames();
                        String artistName="";
                        for(String artist:artistNamesList){
                            artistName=artistName+artist+" ";
                        }
                        autoCompleteData.add(autoSong.getTitle()+"+"+artistName);
                        size++;
                    }
                    if(searchView.getEtInput().equals(playText)){
                        dbData.addAll(completeData);
                        searchView.lvTipslayout();
                        autoCompleteAdapter.notifyDataSetChanged();
                    }

                }
            }
        };
        QueryThread queryThread=new QueryThread(invoker,handler);
        Thread thread=new Thread(queryThread);
        thread.start();
    }

    public void textSearch(final String text){
        GetSongCommand getSongCommand = new GetSongCommand(getResources(), text);
        Invoker invoker = new Invoker();
        invoker.setTransferCommand(getSongCommand);
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String autoCompletemsg = msg.getData().getString("json");
                List<Song> searchData=new ArrayList<>();
                searchData=getdbData(autoCompletemsg);
                if(invaliFla){
                    for(Song song:dbData){
                        if(song.getTitle().contains(text)){
                            resultData.add(song);
                        }else{
                            for(int i=0;i<song.getArtistNames().size();i++){
                                if(song.getArtistNames().get(i).contains(text)){
                                    resultData.add(song);
                                }
                            }
                            if(song.getAlbumName().contains(text)){
                                resultData.add(song);
                            }
                        }
                    }

                }
                resultData.clear();
                resultData.addAll(searchData);
                Log.i("OnlineSearch367",Integer.toString(searchData.size()));
                resultData=sortSong(resultData);
                resultAdapter = new SearchAdapter(OnlineSearchActivity.this, resultData);
                lvResults.setAdapter(resultAdapter);
            }
        };
        QueryThread queryThread=new QueryThread(invoker,handler);
        Thread thread=new Thread(queryThread);
        thread.start();
    }
    public List<Song> getdbData(String json){
        List<Song> completeData=new ArrayList<>();
        try {
            if(jsonParser.typeOf(json).equals("invalidInfo")){
                invaliFla=true;
                Log.i("OnlineSearchActivity362",jsonParser.parseInvalidInfo(json));
            }else {
                completeData = jsonParser.parseSongs(json);
                invaliFla=false;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        completeData=sortSong(completeData);
        Log.i("OnlineSearch392",Integer.toString(completeData.size()));
        return completeData;
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Log.i("OnlineSearchActivity386","finish");
        OnlineSearchActivity.this.finish();
    }
    public ArrayList<Song> sortSong(List<Song> songs){
        Set<Song> songSet=new TreeSet<>(new Comparator<Song>() {
            @Override
            public int compare(Song o1, Song o2) {
                return o1.getSongId()-o2.getSongId();
            }
        });
        songSet.addAll(songs);
        return new ArrayList<Song>(songSet);
    }
    public void closeActivity(){
        OnlineSearchActivity.this.finish();
    }
}
